package com.bootdo.clouddo.task;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.config.TaskConfig;
import com.bootdo.clouddo.domain.baidu.ImageDO;
import com.bootdo.clouddo.service.baidu.IImageService;

@Component
public class BaiduImageTask {

    private static final Logger logger = LoggerFactory.getLogger(BaiduImageTask.class);
    
    private static final String URL = "https://image.baidu.com/channel/listjson";
    
    private static final String[] tags = {"明星","美女", "壁纸", "高校", "宠物", "摄影", "设计"};
    
    @Autowired
    private IImageService imageService;


    @Async("myExecutor")
	@Scheduled(cron="0 0 2,3,4,5,6,7,15,16,17,18 * * ?")
    public void hostSocket() {
    	if(!TaskConfig.baiduImageTaskRun)
    		return;
		Map<String, String> param = new HashMap<>();
		while(true){
			String tag = tags[(int)(Math.random() * tags.length)];
			for (int i = 2; i < 5; i++) {
			    param.put("rn", 30 +"");
				param.put("pn", i +"");
				param.put("tag1", tag);
				try {
					getImgInfo(param);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
    	
    }
	
	private Integer getImgInfo(Map<String, String> param) {
		Integer count = 0;
		try {
			count = getRequest(URL + "?rn={rn}&ie=utf8&pn={pn}&tag1={tag1}", param);
		} catch (Exception e) {
			e.getSuppressed();
		}
		return count;
	}
	
	/**
     * 向目的URL发送get请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
	public Integer getRequest(String url, Map<String, String> params){
    	try {
    		Thread.sleep(6000);
		} catch (Exception e) {
    		e.printStackTrace();
		}
    	Integer count = 0;
    	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    	requestFactory.setConnectTimeout(3000);// 设置超时
    	requestFactory.setReadTimeout(3000);
        RestTemplate client = getInstance(requestFactory);
        String re =  client.getForObject(url, String.class,  params);
        JSONObject result = JSONObject.parseObject(re);
        if(result != null) {
        	JSONArray data = result.getJSONArray("data");
        	if(data != null) {
        		for (int i = 0; i < data.size(); i++) {
					JSONObject jo = data.getJSONObject(i);
					if(jo != null) {
						ImageDO image = jo.toJavaObject(ImageDO.class);
						if(image != null && image.getId() != null) {
							try {
								try {
						    		Thread.sleep(66);
								} catch (Exception e) {
						    		e.printStackTrace();
								}
								if(!imageService.exists(image.getId())) {
									logger.info("成功拉取到一张图片数据："+JSONObject.toJSONString(image));
									image.setSource(ImageDO.TYPE_BAIDU);
									imageService.save(image);
									count ++;
								}else {
									//logger.info("发现重复数据:" + image.getId());
									// System.out.print(".");
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
        	}
        }
        return count;
        //return client.getForObject(url, JSONObject.class,  params);
    }
	
	public static RestTemplate getInstance(SimpleClientHttpRequestFactory requestFactory) {
	    RestTemplate restTemplate = new RestTemplate(requestFactory);
	    List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
	    for (HttpMessageConverter<?> httpMessageConverter : list) {
	        if(httpMessageConverter instanceof StringHttpMessageConverter) {
	            ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
	        }
	    }
	    return restTemplate;
	}

//    
//    public String getHot(String before) throws InterruptedException{
//    	Map<String, String> params = new LinkedHashMap<>();
//    	params.putAll(param);
//	    params.put("src", "web");
//	    params.put("limit", "50");
//	    params.put("category", "all");
//	    params.put("recomment", "1");
//	    params.put("before", before);
//    	
//	    //发送Post数据并返回数据
//	    JSONObject resultVo = JuejinUtils.getRequest(JuejinApiConfig.HOT_RECOMMENT + "?category=all&limit={limit}&recomment={recomment}&before={before}", params);
//	    
//	    if(resultVo == null || !StringUtils.equals(resultVo.getString("m"), "ok"))
//	    	return null;
//	    
//	    JSONArray list = resultVo.getJSONObject("d").getJSONObject("entry").getJSONArray("entrylist");
//	    if(list == null || list.isEmpty())
//	    	return null;
//	    
//	    for (Object obj : list) {
//	    	Thread.sleep(500);
//			JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(obj));
//	    	PostDO post = json.toJavaObject(PostDO.class);
//	    	//获取postId
//	    	boolean result = savePost(post);
//	    	if(result) {
//	    		saveTag(post);
//	    		saveCategory(post);
//	    		savePostDetail(post);
//	    		saveUser(post);
//	    		logger.info("成功拉取一条数据:" + JSONObject.toJSONString(post));
//	    	}
//	    	before = json.getString("verifyCreatedAt");
//		}
//	    return before;
//    }
//    
}
